import React, { useEffect, useState } from 'react'
import './index.scss'
import NavBar from '../../../components/nav-bar'
import { message } from '../../../components/message'
import right_icon from '../images/right_icon.png'
import { useHistory } from 'react-router-dom'
import axios from '../.../../../../utils/axios'
import lrz from 'lrz'

export default function Edit() {
  const [info, setInfo] = useState({})

  const history = useHistory()
  const list = [
    { name: '头像', value: info.avatar },
    { name: '昵称', value: info.username },
    { name: '年龄', value: info.age },
    { name: '地区', value: info.area },
    { name: '个性签名', value: info.signature },
  ]
  useEffect(() => {
    query()
  }, [])
  const query = () => {
    axios.get('user/getUserInfo').then((res) => {
      setInfo(res.data.data[0])
      console.log(res.data.data[0])
    })
  }
  // 提交头像
  const getImg = (obj) => {
    console.log(obj.target[0])
    console.log(obj.target.files, 12)
    if (obj?.target?.files) {
      let files = obj?.target?.files[0]
      if (files?.type.indexOf('image') === 0) {
        let reader = new FileReader() //创建FileReader对象实例reader
        reader.readAsDataURL(files) //将图片url转换为base64码
        reader.onload = function (e) {
          let newUrl = e.target.result
          // 压缩
          lrz(newUrl).then((res) => {
            axios
              .post('/user/editUserInfo', { avatar: res.base64 })
              .then((res) => {
                if (res.data.code === 0) {
                  // 提交成功,刷新信息
                  message('提交成功')
                   query()
                }
              })
          })
        }
      }
    }
  }
  const handleSubmit = (e) => {
    console.log(e)
  }
  return (
    <div className="personal-information-edit">
      <NavBar roomName="编辑个人信息" showRight={false}></NavBar>
      <form onChange={getImg} onSubmit={handleSubmit}>
        {list.map((item, index) => (
          <div
            className="personal-information-edit-input-box"
            key={item.name}
            onClick={() => {
              if (item.name === '头像') return
              history.push(`/edit-detail?name=${item.name}&value=${item.value}`)
            }}
          >
            <span>{item.name}</span>
            {item.name === '头像' ? (
              <div className="edit-input">
                <div className=" edit-detail-img">
                  上传头像
                  <input type="file" accept="image/*"></input>
                </div>
                <img src={item.value} className='input-avatar' style={{borderRadius:'50%'}} alt=">" />
              </div>
            ) : (
              <div className="edit-input">{item.value}</div>
            )}

            <img src={right_icon} alt=">" />
          </div>
        ))}
      </form>
    </div>
  )
}
